package guinew.view;

import inout.XMLWriter;
import inout.XmlDomWriter;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.ParserConfigurationException;

import redsig.redaction.Redacter;
import redsig.signature.Signature;


import core.Adapter;


/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI Builder, which is free for non-commercial use. If Jigloo is being used commercially (ie, by a corporation, company or business for any purpose whatever) then you should purchase a license for each developer using Jigloo. Please visit www.cloudgarden.com for details. Use of Jigloo implies acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */

@SuppressWarnings("serial")
public class ExportView extends javax.swing.JFrame implements Runnable{
	private JPanel mainPanel;
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JButton saveButton;
	private JTextArea exportFile;
	private JTextArea importFile;
	private File file;
	/**
	 * @uml.property  name="writer"
	 * @uml.associationEnd  
	 */
//	private XMLWriter writer = null;
	private XmlDomWriter writer = null;
	private DefaultMutableTreeNode root;
	private boolean keepStructure;
	private JFileChooser fileChooser = null;
	private JFrame parent;
	
	public ExportView(File file, DefaultMutableTreeNode root, boolean keepStructure, JFrame parent) {
		super();
		this.file = file;
		this.root = root;
		this.keepStructure = keepStructure;
		this.parent = parent;
	}
	
	public ExportView(JFrame parent) {
		super();
		this.file = Adapter.getCurrentFile();
		this.root = Adapter.getTreeBuilder().getRoot();
		this.keepStructure = true;
		this.parent = parent;
	}

	/**
	 * Initializes the GUI and its Components
	 */
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setResizable(false);
			this.setTitle("Redactable Trees - Exporter");
			
			mainPanel = new JPanel();
			getContentPane().add(mainPanel, BorderLayout.CENTER);
			mainPanel.setLayout(null);
			mainPanel.setPreferredSize(new java.awt.Dimension(692, 606));
				
			jScrollPane1 = new JScrollPane();
			mainPanel.add(jScrollPane1);
			jScrollPane1.setBounds(12, 12, 327, 549);
			jScrollPane1.setBorder(BorderFactory.createTitledBorder("Imported File"));
					
			importFile = new JTextArea();
			jScrollPane1.setViewportView(importFile);
			importFile.setBounds(12, 12, 327, 549);
			importFile.setOpaque(false);
			importFile.setEditable(false);
			importFile.setText(readFile(file));
					
				
			jScrollPane2 = new JScrollPane();
			mainPanel.add(jScrollPane2);
			jScrollPane2.setBounds(351, 12, 327, 549);
			jScrollPane2.setBorder(BorderFactory.createTitledBorder("Recreated File"));

			exportFile = new JTextArea();
			jScrollPane2.setViewportView(exportFile);
			exportFile.setBounds(351, 12, 327, 549);
			exportFile.setOpaque(false);
			exportFile.setEditable(false);
			exportFile.setText(writer.getContent());

			saveButton = new JButton();
			mainPanel.add(saveButton);
			saveButton.setText("Save");
			saveButton.setBounds(597, 573, 81, 28);
			saveButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					saveFile();
					
				}	
			});

			pack();
			this.setSize(700, 644);
			this.setLocationRelativeTo(null);
			this.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void saveFile() {
		File fileToSave = null;
		if(fileChooser  == null)
			fileChooser = new JFileChooser();
		fileChooser.setDialogTitle("Save as...");
		fileChooser.setApproveButtonText("Save");

		int returnVal = fileChooser.showOpenDialog(rootPane);
		if(returnVal == JFileChooser.APPROVE_OPTION){
			fileToSave = fileChooser.getSelectedFile();
			
			if(writeToFile(fileToSave)){
				JOptionPane.showMessageDialog(this, new String("The File has been exported to " 
						+ fileToSave.getAbsolutePath() + "/" + fileToSave.getName()));
			}
		}
	
		
	}

	@SuppressWarnings("finally")
	private boolean writeToFile(File file) {
		boolean result = false;
		try { 
			OutputStream out = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(out);
			osw.write(writer.getContent());
			osw.close();
			out.close();
			
			if(Redacter.checkForRedaction(Adapter.getMap().get(root), false)){
				writeSignatureFile(file);
			}
			result = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		finally{
			Adapter.redactedFileSize = file.length();
			Adapter.printStatistics();
			return result;
		}
	}
	
	private void writeSignatureFile(File file){
		String filename = file.getAbsolutePath().substring(0, file.getAbsolutePath().length()-3) + "sig";
		File signatureFile = new File(filename);
		OutputStream out;
		try {
			out = new FileOutputStream(signatureFile);
			OutputStreamWriter osw = new OutputStreamWriter(out);
			//osw.write(writer.getSignatureContent());
			Signature sig = Adapter.getDocSigner().getSignatureFile();
			if(sig != null){
				osw.write("Signature: \n" + Adapter.byteToBase64(sig.getSignature()));
			}
			osw.close();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}

	/**
	 * Reads the input file and builds a string with its content
	 * @param file the input file
	 * @return the content of the input file
	 */
	private String readFile(File file){
		String content = "";
		try {
			FileReader in = new FileReader(file);
		    BufferedReader reader = new BufferedReader(in);
		    String line = null;
		    while ((line = reader.readLine()) != null) {
		    	content = content+line+"\n";
		    }
		} catch (IOException x) {
		    System.err.println(x);
		}		
		return content;
	}


	public void run() {
//		writer = new XMLWriter(Adapter.getMap().get(root), keepStructure);
		try {
			writer = new XmlDomWriter(Adapter.getMap().get(root));
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		initGUI();	
	}
}
